package me.fung.keen.component.message

import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import me.fung.keen.app.ShowAble

val msg = MessageModel()
val localMessage = compositionLocalOf { msg }

class MessageContent : ShowAble {
    @Composable
    override fun show(modifier: Modifier) {
        val state = localMessage.current
        val color: Color = when (state.data.messageType) {
            MessageType.Info -> MaterialTheme.colors.surface
            MessageType.Warning -> MaterialTheme.colors.secondary
            MessageType.Error -> MaterialTheme.colors.error
            MessageType.None -> MaterialTheme.colors.surface
        }.copy(alpha = 0.95f)

        val width = remember { Animatable(0f) }
        LaunchedEffect(state.data) {
            width.animateTo(if (state.data.done) 0f else 1f)
            if (state.data.messageType in listOf(MessageType.Info, MessageType.Warning) && !state.data.done) {
                delay(7000)
                state.done()
            }
        }
        Box(modifier, contentAlignment = Alignment.BottomCenter) {
            Row(
                modifier = Modifier.fillMaxWidth(width.value).fillMaxHeight().background(color).padding(5.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(text = state.data.message, color = contentColorFor(color))
                IconButton(
                    onClick = { state.done() }
                ) {
                    Icon(Icons.Default.Close, "关闭")
                }
            }
        }
    }

}